import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './index.less';
import { isZiGuanEvir } from '../../../utils/commonFunc';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Tabs, Rate, Tree, Switch, message } from 'antd';
import { SingleDateC, SecondHeaderC, SelectC, FirstHeaderC, PrimaryC, PrimaryGhostC, InputC } from '../../../comps';
import moment from 'moment';
import TradeDirectionC from './tradeDirection';
import RelatedRulesC from './relatedRules';
import AssetIndexC from './assetIndex';
import dictData from './config';
import { formatDictData } from '../../../utils/utils';
import assetIndex from './assetIndex';
const { TabPane } = Tabs;
const { TreeNode } = Tree;
const FormItem = Form.Item;
const FormItemLayout = {
  labelCol: {
    lg: { span: 7, offset: 0 },
    xl: { span: 7, offset: 0 },
    xxl: { span: 7, offset: 0 },
  },
  wrapperCol: {
    lg: { span: 15, offset: 0 },
    xl: { span: 15, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};
function checkAll(item) {
  return item.checked == false;
}
@Form.create()
class AddRuleC extends PureComponent {
  state = {
    isAllSelect: false, //账户组是否全选
    admin: undefined, //是否是管理员
    productData: [], //产品下拉
    activeKey: '1', //标签页 默认资产指标
    directionObj: {}, //存储交易方向
    majorRuleIds: [], //存储管理规则
    assetIndexObj: undefined, //存储资产指标
  };

  componentDidMount() {
    const {
      limitManagemen: { productList = [] },
    } = this.props;
    this.setState({ productData: _.cloneDeep(productList) });
  }
  componentWillUnmount() {
    //离开前清空缓存数据
  }

  //点击确定
  submit = () => {
    this.saveTabData('submit'); // 保存tab数据
  };
  //格式化提交参数 几个子组件的数据 在这里合并 提交给后端
  formatSubmitData = () => {
    const {
      form: { validateFields },
      detailData,
      dispatch,
    } = this.props;
    const { directionObj, majorRuleIds, assetIndexObj } = this.state;
    validateFields((err, fieldsValue) => {
      if (err) return;
      if (!fieldsValue.priority) {
        message.warning('优先级必选');
        return;
      }
      if (!assetIndexObj) return; //资产指标有值才可以新增
      let switchValues = {};
      if (JSON.stringify(directionObj) == '{}') {
        let tempArr = detailData && detailData.switchList ? detailData.switchList : dictData.switchList; //考虑到用户未点击设置，交易方向设置初始化入参
        switchValues = this.getTradedirect(tempArr);
      } else {
        switchValues = directionObj;
      }
      console.log('交易方向', switchValues);
      //考虑到用户未点击设置，关联规则初始化入参
      let majorRuleIdsValues = !majorRuleIds.length ? (detailData && detailData.majorRuleIds) || [] : majorRuleIds;
      console.log('关联规则', majorRuleIdsValues);
      console.log('资产指标', assetIndexObj);
      let valveValueUnit = fieldsValue.absControlFlag == true ? '元' : '%';
      const createTime = moment().format('YYYY-MM-DD');
      const createPerson = isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId');
      let controlValue = typeof fieldsValue.controlValue == 'string' ? fieldsValue.controlValue.split(' ') : fieldsValue.controlValue; //当控制类别为字符串时转换成数组，因后端该字段设置为数组
      const arr = controlValue.filter((item) => item == 'ALL');
      if (arr && arr.length) controlValue = ['ALL'];
      const tenant = !isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem('maat-antd-pro-tenant');
      let params = {
        ...fieldsValue,
        ...switchValues,
        ...assetIndexObj,
        majorRuleIds: majorRuleIdsValues,
        effectiveTime: fieldsValue.effectiveTime.format('YYYY-MM-DD'),
        expireTime: fieldsValue.expireTime.format('YYYY-MM-DD'),
        ruleState: fieldsValue.ruleState == true ? 1 : 2,
        singleTargetControl: assetIndexObj.singleTargetControl == '1' ? true : false,
        pecent: assetIndexObj.pecent == '1' ? true : false,
        valveValueUnit,
        createTime,
        createPerson,
        controlValue: controlValue,
        tenant,
        ruleCategory: Number(fieldsValue.ruleCategory),
        ruleApplyObj: Number(fieldsValue.ruleApplyObj),
        controlLay: Number(fieldsValue.controlLay),
      };
      params.controlMethod = Number(params.controlMethod);
      // const controlDebar = data.controlDebar ? data.controlDebar : [];//排除账户
      console.log('提交的数据', params);
      var that = this;
      dispatch({
        type: this.props.type == 2 ? 'limitManagemen/modifyRule' : 'limitManagemen/createRule',
        payload: {
          ...params,
          ruleId: this.props.type == 2 ? detailData?.ruleId : undefined, //编辑的时候有id
          ruleNo: this.props.type == 2 ? detailData?.ruleNo : undefined, //编辑的时候有id
        },
      }).then((res) => {
        if (res && res.success) {
          message.success(this.props.type != 2 ? '新增限额信息成功' : '编辑限额信息成功');
          that.props.onOk();
        } else {
          let msg = this.props.type != 2 ? '新增限额信息失败' : '编辑限额信息失败';
          message.error(res ? res.message || msg : msg);
        }
      });
    });
  };
  //获取交易方向入参格式
  getTradedirect = (switchList) => {
    console.log(switchList);
    var switchValues = {};
    switchList.map((item) => {
      switchValues[item.value] = item.checked;
    });
    switchValues.transactionDirectionControl = !switchList.some(checkAll);
    return switchValues;
  };
  //tab切换
  tabChange = (e) => {
    this.saveTabData(); // 保存tab数据
    this.setState({ activeKey: e });
  };
  saveTabData = (type) => {
    if (this.state.activeKey == 2) {
      //保存交易方向 修改内容
      const directionObj = this.state.TradeDirection && this.state.TradeDirection.submit();
      this.setState(
        {
          directionObj,
        },
        () => {
          if (type == 'submit') {
            //提交获取的数据有延迟 所以等state渲染完
            this.formatSubmitData();
          }
        },
      );
    } else if (this.state.activeKey == 3) {
      //保存关联规则 修改内容
      const arr = this.state.relatedRef && this.state.relatedRef.state.choosedData;
      this.setState(
        {
          majorRuleIds: arr, //关联规则
        },
        () => {
          if (type == 'submit') {
            //提交获取的数据有延迟 所以等state渲染完
            this.formatSubmitData();
          }
        },
      );
    } else {
      //资产指标
      const obj = this.state.AssetIndex && this.state.AssetIndex.submit();
      this.setState(
        {
          assetIndexObj: obj,
        },
        () => {
          if (type == 'submit') {
            //提交获取的数据有延迟 所以等state渲染完
            this.formatSubmitData();
          }
        },
      );
    }
  };

  /*
    产品组件
    列表结构，默认插入第一条数据“全选当前存续产品和新增产品”（替代“全部”）
    支持多选（选了第一条数据，后面的就不给选了）
    下拉数据中不包含到期产品
  */
  //产品变更
  controlValueChange = (val) => {
    console.log(val);
    const { productData } = this.state;
    const arr = val && val.filter((item) => item == 'ALL');
    if (arr && arr.length) {
      productData.map((item) => {
        if (item.value !== 'ALL') item.disabled = true;
      });
      this.setState({
        productData: [...productData],
      });
      return val.filter((item) => item == 'ALL');
    } else {
      productData.map((item) => {
        if (item.value !== 'ALL') item.disabled = false;
      });
      this.setState({
        productData: [...productData],
      });
      return val;
    }
  };

  render() {
    const {
      form: { getFieldDecorator, getFieldValue },
      detailData = {},
      limitManagemen: { dictMap = {} },
      loading,
    } = this.props;
    const { productData, activeKey } = this.state;
    return (
      <div className={myStyle.addRule}>
        <div style={{ height: 'calc(100vh - 180px', overflowY: 'auto' }}>
          <FirstHeaderC title={this.props.type == 1 ? '限额设置-新增' : '限额设置-编辑'} />
          <Row>
            <Col className={myStyle.myRuleDesc}>
              <InputC
                form={this.props.form}
                dataIndex='ruleDesc'
                title='风险说明'
                initialValue={detailData.ruleDesc || ''}
                rules={[{ required: true, message: '请填写风险说明' }]}
              />
            </Col>
          </Row>
          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title='基本信息' />
          </div>
          <Row>
            <Col span={6}>
              <SelectC
                form={this.props.form}
                dataIndex='ruleApplyObj'
                title='风险类别'
                initialValue={detailData.ruleApplyObj ? detailData.ruleApplyObj.toString() : '1'}
                dataSource={dictData.applyObj}
                rules={[{ required: true, message: '请选择风险类别' }]}
              />
            </Col>
            <Col span={6}>
              <FormItem label='优先级' {...FormItemLayout}>
                {getFieldDecorator('priority', {
                  initialValue: detailData.priority || 5,
                  rules: [{ required: true, message: '请选择优先级' }],
                })(<Rate count={9} className={myStyle.myStar} />)}
              </FormItem>
            </Col>
            <Col span={6}>
              <SelectC
                form={this.props.form}
                dataIndex='ruleCategory'
                title='风险类型'
                initialValue={detailData.ruleCategory ? detailData.ruleCategory.toString() : undefined}
                dataSource={dictMap.risk_category ? formatDictData(dictMap.risk_category) : []}
                rules={[{ required: true, message: '请选择风险类型' }]}
              />
            </Col>
            <Col span={6}>
              <SelectC
                form={this.props.form}
                dataIndex='ruleType'
                title='风险等级'
                initialValue={detailData.ruleType}
                dataSource={dictMap.risk_level ? formatDictData(dictMap.risk_level) : []}
                rules={[{ required: true, message: '请选择风险等级' }]}
              />
            </Col>
          </Row>
          <Row>
            <Col span={6}>
              <SingleDateC
                title='生效日期'
                form={this.props.form}
                initialValue={detailData.effectiveTime ? moment(detailData.effectiveTime) : moment()}
                disableBegin={moment().subtract(1, 'days')}
                disableEnd={getFieldValue('expireTime')}
                dataIndex='effectiveTime'
                allowClear={false}
                rules={[{ required: true, message: '请填写生效日期' }]}
              />
            </Col>
            <Col span={6}>
              <SingleDateC
                title='失效日期'
                form={this.props.form}
                initialValue={detailData.expireTime ? moment(detailData.expireTime) : moment('2099-12-31')}
                disableBegin={getFieldValue('effectiveTime')}
                dataIndex='expireTime'
                allowClear={false}
                rules={[{ required: true, message: '请填写失效日期' }]}
              />
            </Col>
          </Row>
          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title='账户信息' />
          </div>
          <Row>
            <Col span={6}>
              <SelectC
                form={this.props.form}
                dataIndex='controlLay'
                title='账户层次'
                initialValue={detailData.controlLay || '2'}
                dataSource={dictData.controlLay}
                rules={[{ required: true, message: '请选择账户层次' }]}
              />
            </Col>
            <Col span={6}>
              <SelectC
                form={this.props.form}
                title='产品'
                dataIndex='controlValue'
                initialValue={detailData.controlValue}
                // onChange={this.controlValueChange}
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                showSearch={true}
                dataSource={productData}
                isMultiple={true}
                allowClear={true}
                getValueFromEvent={this.controlValueChange}
                rules={[{ required: true, message: '请选择产品' }]}
              />
            </Col>
            <Col span={6}>
              <SelectC
                form={this.props.form}
                dataIndex='controlMethod'
                title='账户控制'
                initialValue={detailData.controlMethod}
                dataSource={dictData.controlMethod}
                rules={[{ required: true, message: '请选择账户控制' }]}
              />
            </Col>
          </Row>
          <div className={myStyle.tabsCls}>
            <Tabs onChange={this.tabChange} type='card' activeKey={activeKey} tabBarGutter={4}>
              <TabPane tab='资产指标' key='1'>
                <AssetIndexC detailData={detailData} changeDetailData={this.props.changeDetailData} onRef={(ref) => this.setState({ AssetIndex: ref })} />
              </TabPane>
              <TabPane tab='交易方向' key='2'>
                <TradeDirectionC dataList={detailData.switchList || dictData.switchList} onRef={(ref) => this.setState({ TradeDirection: ref })} />
              </TabPane>
              <TabPane tab='关联规则' key='3'>
                <RelatedRulesC
                  modalType={this.props.type}
                  choosedData={detailData.majorRuleIds || []}
                  ruleId={detailData.ruleId}
                  tenant={!isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem('maat-antd-pro-tenant')}
                  onRef={(ref) => this.setState({ relatedRef: ref })}
                />
              </TabPane>
            </Tabs>
          </div>
          <div className={myStyle.ruleStatus}>
            <FormItem label={'启用'}>
              {getFieldDecorator('ruleState', {
                initialValue: detailData.ruleState ? (detailData.ruleState == 1 ? true : false) : true,
                valuePropName: 'checked',
              })(<Switch checkedChildren='开' unCheckedChildren='关' />)}
            </FormItem>
          </div>
        </div>

        <div className={myStyle.saveBtn}>
          <PrimaryGhostC title='取消' onClick={() => this.props.onCancle()} style={{ marginRight: '16px' }} />
          <PrimaryC title='确定' loading={loading.effects['limitManagemen/createRule'] == true || loading.effects['limitManagemen/modifyRule'] == true} onClick={this.submit} />
        </div>
      </div>
    );
  }
}
export default connect(({ limitManagemen, dictionaryM, userM: user, loading }) => ({
  limitManagemen,
  dictionaryM,
  user,
  loading,
}))(AddRuleC);
